//
//  SYWordViewController.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/5/8.
//  Copyright © 2019年 SanYi. All rights reserved.
//

#import "SYWordViewController.h"
#import <QuickLook/QuickLook.h>


@interface SYWordViewController () <QLPreviewControllerDataSource ,QLPreviewControllerDelegate>

@property (nonatomic, copy) NSString *path;
@property (nonatomic, strong) QLPreviewController *qlPC;
@property (strong, nonatomic) NSMutableData *receiveData;
@end

@implementation SYWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // self.view.backgroundColor = [UIColor yellowColor];
    
    
    [self isLoading];
    UIButton *fanhuiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [fanhuiBtn setImage:[UIImage imageNamed:@"zy_ppt_fanhui"] forState:UIControlStateNormal];
    fanhuiBtn.frame = CGRectMake(20, 20, 40, 40);
    [fanhuiBtn addTarget:self action:@selector(fanhuiBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:fanhuiBtn];
    
}
- (void)fanhuiBtnClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)requestdataDownLoadFile:(NSString *)filePath {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD mj_showMessage:@"正在下载..." toView:self.view];
    self.urlStr = [self.urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [SYDownloadFile downloadFileWithUrl:self.urlStr success:^(id responseObject) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        [weakSelf addPreview];
        
    } failure:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        [MBProgressHUD zr_showError:@"下载失败"];
        [NSObject executeRunloop:^{
            [weakSelf fanhuiBtnClick];
        } afterDelay:1];
    } progress:^(float progress, long long bytesRead) {
       // [MBProgressHUD mj_hideHUDForView:self.view];
    } savePath:filePath];
    
    
}
#pragma mark 判断是否需要下载
- (void)isLoading
{
    NSString *urlStr = _urlStr;
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    _path = path;
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    if (data == nil) {
        [self writeToCacheWithUrl:urlStr];
    } else {
        [self addPreview];
    }
    
    
}
#pragma mark 写入缓存
- (void)writeToCacheWithUrl:(NSString *)urlStr
{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取document路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
    //写入路径
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    
    [data writeToFile:path atomically:YES];
    _path = path;
    [self requestdataDownLoadFile:path];
    
}
- (void)addPreview
{
    _qlPC = [[QLPreviewController alloc] init];
//    _qlPC.view.frame = CGRectMake(0, 64, self.view.width, self.view.height - 64);
    _qlPC.dataSource = self;
    _qlPC.delegate = self;
    [self addChildViewController:_qlPC];
    [self.view addSubview:_qlPC.view];
    [self.qlPC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(50);
        make.left.bottom.right.equalTo(self.view);
    }];
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return [NSURL fileURLWithPathComponents:@[_path]];
}
@end
